var mysql = require('mysql');

class Base {
    constructor() {
        this.dataBaseConfig = {
            host: 'localhost',
            port: '3306',
            user: 'root',
            password: '0610',
            database: 'stuManagePlatform'
        };
    }

    QueryMysql(sql, params, callback) {
        //创建连接
        let connection = mysql.createConnection(this.dataBaseConfig);
        connection.connect((err) => {
            if (err) {
                console.log(sql + " 语句，数据库连接失败");
                throw err;
            }
        })


        connection.query(sql, params, (err, results, fields) => {
            if (err) {
                console.log(sql + " 语句，数据库操作失败");
                throw err;
            }

            try {
                if (fields != undefined) {
                    //results 以行为单位返回数据
                    //fields 以列为单位，返回字段属性的信息
                    let finalResults = JSON.parse(JSON.stringify(results));
                    let finalFields = JSON.parse(JSON.stringify(fields));
                    //函数存在则执行
                    callback && callback(finalResults, finalFields);
                } else {
                    callback && callback(1, 1);
                }
            } catch (err) {
                console.log("解析数据失败,Catch:" + err.message)
            }
            //端开连接
            connection.end((err) => {
                if (err) {
                    console.log(sql, " 语句，数据库关闭失败");
                    throw err;
                }
            })
        })
    }
}


module.exports = {Base}